#include "databasemanager.h"

#include <QDebug>
#include <QSqlError>

DataBaseManager::DataBaseManager(QObject *parent)
    : QObject{parent}
    ,dbPath(":/sqllite/zyTechManSys.db")
{
    db = QSqlDatabase::addDatabase("QSQLITE");
}

DataBaseManager::~DataBaseManager()
{
    closeDatabase();
}

DataBaseManager &DataBaseManager::getInstance()
{
    static DataBaseManager instance;
    return instance;
}

bool DataBaseManager::openDatabase(const QString &dbPath)
{
    if (db.isOpen()) {
        db.close();
    }

    db.setDatabaseName(dbPath);

    if (!db.open()) {
        qDebug() << "Failed to open database:" << db.lastError().text();
        return false;
    }

    qDebug() << "Database opened successfully";
    return true;
}

void DataBaseManager::closeDatabase()
{
    if (db.isOpen()) {
        db.close();
        qDebug() << "Database closed";
    }
}

QString DataBaseManager::getDatabasePath() const
{
    return dbPath;
}

void DataBaseManager::setDatabasePath(const QString &path)
{
    if (dbPath == path) {
        return;
    }
    dbPath = path;
    openDatabase(dbPath);
}